package edu.uwm.cs552;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;


/**
 * Render a terrain with a little icon showing the visual rendering of 
 * a terrain.
 */
public class TopographyRenderer extends DefaultListCellRenderer {
	/**
	 * Keep Eclipse Happy
	 */
	private static final long serialVersionUID = 1L;
	protected static final int ICON_SIZE = 20;
	@SuppressWarnings("rawtypes")
	protected List<Topography> topographies = new ArrayList<Topography>();
	protected ImageIcon[] icons;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Component getListCellRendererComponent(JList list,
			Object value,
			int index,
			boolean isSelected,
			boolean hasFocus) {
		for(Terrain t : Terrain.values())
			topographies.add(t);
		for(Barrier b : Barrier.values())
			topographies.add(b);
		if (icons == null) {					
			icons = new ImageIcon[topographies.size()];
			for (int i=0; i < topographies.size(); ++i) {
				BufferedImage im = new BufferedImage(ICON_SIZE,ICON_SIZE, BufferedImage.TYPE_INT_ARGB);
				Graphics g = im.getGraphics();
				g.translate(getIconWidth(i), getIconHeight(i));
				if (i < topographies.size())
					topographies.get(i).draw(g, topographies.get(i).getOrigin(), ICON_SIZE, false);
				icons[i] = new ImageIcon(im);
			}
			//drawIcons(terrains, barriers);
		}
		JLabel label =
			(JLabel)super.getListCellRendererComponent(list,
					value == Terrain.TERASE ? "[Erase terrain]" : value == Barrier.BERASE ? "[Erase barrier]" : value,
					index,
					isSelected,
					hasFocus);
		if (value instanceof Terrain) {
			int i = ((Terrain)value).ordinal();
			label.setIcon(icons[i]);
		} else if(value instanceof Barrier){
			int i = ((Barrier)value).ordinal();
			label.setIcon(icons[i + Terrain.values().length]);
		} else {
			// Clear old icon; needed in 1st release of JDK 1.2
			label.setIcon(icons[topographies.size()]); 
		}
		return(label);
	}
	
	private int getIconWidth(int i) {
		if(topographies.get(i) instanceof Barrier)
			return ICON_SIZE/10;
		return ICON_SIZE/2;
	}
	
	private int getIconHeight(int i) {
		return ICON_SIZE/2;
	}
}
